package com.huaqing.util;

import ch.qos.logback.classic.Logger;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @program: javatrainingfirstweek
 * @Description: 将对象转换为JOSN
 * @author: 24562
 * @date: 2022/4/8 18:27
 */
@Slf4j
public class TxtUtil implements DataOperation {

//    public void writer(Object o){
//        String json= JSON.toJSONString(o);
//        BufferedWriter bw = null;
//        /** 使用try-resource的写法,不把路径写死 **/
//        try {
//            File file = new File("/"+o.getClass().getName()+".txt");
//            if (!file.exists()) {
//                file.createNewFile();
//            }
//            FileWriter fw = new FileWriter(file.getAbsoluteFile());
//            bw = new BufferedWriter(fw);
//            bw.write(json);
//        } catch (IOException e) {
//            e.printStackTrace();// log.error()
//        } finally {
//            try {
//                bw.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }
//
//    public void ReadData(Object o){
//        try {
//            FileReader read = new FileReader("/"+o.getClass().getName()+".txt");
//            BufferedReader br = new BufferedReader(read);
//            String row;
//            while((row = br.readLine())!=null){
//                log.info(row);
//            }
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e){
//            e.printStackTrace();
//        }
//        /** finally语句 **/
//    }

    @Override
    public int dataToFileExport(Object data) {
        String json= JSON.toJSONString(data);
        BufferedWriter bw = null;
        /** 使用try-resource的写法,不把路径写死 **/
        try {
            File file = new File("/"+data.getClass().getName()+".txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            bw = new BufferedWriter(fw);
            bw.write(json);
        } catch (IOException e) {
            e.printStackTrace();// log.error()
            return 1;
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    @Override
    public Object fileToDataImport(File file) {
        try {
            FileReader read = new FileReader(file);
            BufferedReader br = new BufferedReader(read);
            StringBuffer row = new StringBuffer();
            String temp;
            while((temp = br.readLine())!=null){
                row.append(temp);
            }
            return row;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
}
